<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function animalLog(){
		$arr=array(
			'd_id' =>1,
			'animal'=>array(array('id'=>1,'num'=>2),array('id'=>2,'num'=>2),array('id'=>3,'num'=>3)),
			);
		$id = $arr['d_id'];
		foreach ($arr['animal'] as $k => $v) {
			$list[$k]['animal_id'] = $v['id'];
			$list[$k]['num']       = $v['num'];
			$list[$k]['device_id'] = $id;

			$list[$k]['date_y']    = date('Y');
			$list[$k]['date_m']    = date('m');
			$list[$k]['date_d']    = date('d');

			$list[$k]['date_h']    = date('H');
			$list[$k]['add_time']  = time();
		}
		$data=M('animal_log')->addAll($list);
		if ($data) {
			$this->display();
		}
	}
	public function weixin(){
        $appid=C('APP_ID');
        $redirect_uri = urlencode('http://'.C('INT_COM').'/index.php/Home/Index/openid');
        Header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");
    }
	/** 
	 * 微信登陆
	 * @return code 微信code
	 * @return openid 微信openid
	 */
	public function openid(){
        $code=I('get.code');
        $appid=C('APP_ID');
        $secret=C('app_secret');
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code={$code}&grant_type=authorization_code";

        $res=$this->curlGet($url,$type="GET");
        $json=json_decode($res, true);

        $url_info = "https://api.weixin.qq.com/sns/userinfo?access_token=".$json['access_token']."&openid=".$json['openid']."&lang=zh_CN";
        $result=$this->curlGet($url_info,$type="GET");
        
        $userinfo=json_decode($result, true);
        
        session('openid',$userinfo['openid']);
        session('userinfo',$userinfo);
        
        $MODEL = M("User");
        $map['openid']=$userinfo['openid'];
        $data=$MODEL->where($map)->find();
        
        if($data){
            session('uid',$data);
            $this->redirect("Index/index");
        }else{
            $this->redirect("Index/login");
        }
    }
    public function login(){
        if (IS_POST) {
            $name = I('post.username');
            $pwd  = I('post.password');
            $data = M('user')->where(array('username'=>$name,'password'=>md5($pwd)))->find();
            if ($data) {
                if (session('openid')) {
                    if ($data['openid']) {
                        return show(2,"该账号已经绑定了微信号");
                    }
                    $list = array(
                        'openid'=>session('openid'),
                        'weixin_name'=>session('userinfo.nickname'),
                        'photo_id'=>session('userinfo.headimgurl')
                    );
                    M('user')->where('id='.$data['id'])->save($list);
                    
                    $data['openid']=session('openid');
                    $data['photo_id']=session('userinfo.headimgurl');
                    $data['id']=$data['id'];
                }else{
                    return show(2,"请先进行微信登录");
                }
                session('uid',$data);
                // $this->redirect("Project/Index");
                $this->success('登录成功');
            }else{
                $result['status'] = '0';
                $result['message'] = '密码错误';
                $this->ajaxReturn($result);
                return show(0,"账户与密码不匹配");
            }
        }else{
            $this->display();
        }
    }
    public function gettoken(){
    	$appid=C('APP_ID');
        $secret=C('app_secret');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res=$this->curlGet($url,$type="GET");
        $json=json_decode($res, true);

        return $json['access_token'];
    }
    public function getjsticket(){
	    $access_token = $this->gettoken();
	    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi"; // 两小时有效
	    $rurl = $this->curlGet($url);
	    $rurl = json_decode($rurl,true);
	    if($rurl['errcode'] != 0){
	      return false;
	    }else{
	      $jsticket = $rurl['ticket'];
	      return $jsticket;
	    }
	}
	public function getsignature(){
	    $noncestr = 'sdsdsdssd';
	    $jsapi_ticket = $this->getjsticket();
	    $timestamp = time();
	    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	    $string1 = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
	    $signature = sha1($string1);
	    return $signature;
	}
	public function index(){
        if (!session('uid')) {
            // $this->weixin();
            $this->redirect('Index/weixin');
        }
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
        $info = array(
            'id'            =>session('uid.id'),
            'weixin_name'   =>session('uid.weixin_name'),
            'photo_id'      =>session('uid.photo_id'),
            'username'      =>session('uid.username'),
        );
        $this->assign('userInfo',$info);
        $this->assign('data',$data);
		$this->display();
	}
    function curlGet($url,$type="GET"){
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        curl_close($ch);
        return $temp;
    }

}